package cn.ztc.tool.redis.template;

import javax.annotation.PostConstruct;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import cn.ztc.tool.redis.template.serializer.KeySerializer;
import cn.ztc.tool.redis.template.serializer.ValueSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.connection.RedisConnectionFactory;

/**
 * 泛型的RedisTemplate
 *
 * @author 张天赐
 */
@Lazy
@Slf4j
@Component
public class AccurateRedisTemplate<K, V> extends RedisTemplate<K, V> {
    /**
     * 连接工厂
     */
    RedisConnectionFactory factory;

    /**
     * 构造函数
     *
     * @param factory 连接工厂
     */
    AccurateRedisTemplate(RedisConnectionFactory factory) {
        this.factory = factory;
    }

    /**
     * 构建内容
     */
    @PostConstruct
    void init() {
        RedisSerializer<K> keySerializer = new KeySerializer<>();
        RedisSerializer<V> valueSerializer = new ValueSerializer<>();
        // base
        this.setConnectionFactory(this.factory);
        this.setEnableDefaultSerializer(false);
        // -
        this.setKeySerializer(keySerializer);
        this.setValueSerializer(valueSerializer);
        // hash
        this.setHashKeySerializer(keySerializer);
        this.setHashValueSerializer(valueSerializer);
        // init
        this.afterPropertiesSet();
    }
}
